package com.md.album.ui

import android.content.Intent
import android.content.res.Resources.NotFoundException
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.living.filedownloader.db.AlbumDB
import com.md.album.R
import com.md.album.SelectCoverModel
import com.md.album.constant.AlbumConstant
import com.md.album.databinding.ActivityEditAlbumBinding
import com.md.album.db.SelfAlbumDB
import com.md.album.db.SelfAlbumManager
import com.md.album.event.SelfAlbumEventModel
import com.md.basedpc.constant.BaseConstant.SELF_CREATE_ALBUM
import com.md.basedpc.routerservice.NotifyService
import com.md.livingwidget.navigation.PHNavigationBar
import com.md.network.api.Album
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @author liyue
 * created 2021/3/28
 * desc 自建专辑编辑页面
 * todo 导航栏UI和逻辑可以抽象到BaseActivity中，后续再改
 */
const val TMP_TITLE = "tmp_title"
const val TMP_ALBUMID = "tmp_albumid"

class EditSelfAlbumActivity : AppCompatActivity() {
    private lateinit var binding: ActivityEditAlbumBinding
    private lateinit var navBar: PHNavigationBar
    private lateinit var edtTitle: EditText
    private lateinit var edtDesc: EditText
    private lateinit var fltDelete: FrameLayout
    private lateinit var fltCover: FrameLayout
    private lateinit var ivCover: ImageView
    private var resUrl = AlbumConstant.DEFAULT_ALBUM_COVER;
    private var title: String? = ""
    private var albumId = "-1"
    private lateinit var curAlbum: SelfAlbumDB


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityEditAlbumBinding.inflate(LayoutInflater.from(this))
        setContentView(binding.root)
        EventBus.getDefault().register(this)
        initData()
        initView()

    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    private fun initData() {
        title = intent.getStringExtra(TMP_TITLE)
        albumId = intent.getStringExtra(TMP_ALBUMID) ?: "-1"
        curAlbum = SelfAlbumManager.getIns().getAlbumDBById(albumId)
    }

    private fun initView() {
        navBar = binding.navBar
        navBar.right1Tv.visibility = View.VISIBLE
        navBar.right1Tv.setTextColor(resources.getColor(R.color.album_595959))
        navBar.right1Tv.text = resources.getString(R.string.album_save)
        edtTitle = binding.edtTitle
        edtTitle.setText(title)
        edtDesc = binding.edtDesc
        fltDelete = binding.fltDelete
        fltDelete.setOnClickListener {
            edtTitle.setText("")
            fltDelete.visibility = View.GONE
        }
        edtTitle.addTextChangedListener(object : android.text.TextWatcher {
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (!TextUtils.isEmpty(s) && !TextUtils.isEmpty(s?.trim())) {
                    fltDelete.visibility = View.VISIBLE
                } else {
                    fltDelete.visibility = View.GONE
                }
            }

        })

        navBar.right1Tv.setOnClickListener {
            var model = SelectCoverModel(true, resUrl)
            EventBus.getDefault().post(model)
            updateSelfAlbum()
        }
        navBar.centerTvTitle.text = resources.getString(R.string.album_edit_detail)
        navBar.left1Imgback.setOnClickListener {
            finish()
        }

        fltCover = binding.fltCover
        fltCover.setOnClickListener {
            var intent = Intent(this, SelectCoverActivity::class.java)
            startActivity(intent)
        }
        ivCover = binding.ivCover
        Glide.with(this).load(curAlbum.cover).placeholder(R.drawable.selfalbum_cover_default).into(ivCover)

        edtDesc.setText(curAlbum.desc)
    }

    private fun updateSelfAlbum() {
        var title = edtTitle.text.toString()
        if (TextUtils.isEmpty(title) || TextUtils.isEmpty(title.trim())) {
            Toast.makeText(this, getString(R.string.album_title_empty), Toast.LENGTH_SHORT).show()
            return
        }
        if (("-1").equals(albumId)) {
            Toast.makeText(this, getString(R.string.album_create_fail), Toast.LENGTH_SHORT).show()
            return
        }
        var desc = edtDesc.text.toString()
        curAlbum?.let {
            it.name = title
            it.desc = desc
            it.cover = resUrl
            var isSuc = SelfAlbumManager.getIns().update(it)
            if (isSuc) {
                var model = SelfAlbumEventModel(curAlbum.name, curAlbum.cover, curAlbum.desc)
                EventBus.getDefault().post(model)
                ARouter.getInstance().navigation(NotifyService::class.java).selfAlbumUpdateSuc(SELF_CREATE_ALBUM)
                finish()
            } else {
                Toast.makeText(this, resources.getString(R.string.album_create_fail), Toast.LENGTH_SHORT).show()
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshIcon(model: SelectCoverModel?) {
        model?.let {
            if (model.isShow) {
                resUrl = model!!.resUrl
                Glide.with(this)
                        .load(resUrl)
                        .centerCrop()
                        .apply(RequestOptions.bitmapTransform(CircleCrop()))
                        .into(ivCover)
            }
        }
    }
}